package com.futvan.z.system.zdb;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.common.service.CommonService;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.StringUtil;
import com.futvan.z.framework.util.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
@Controller
public class Z_dbZ_db_create_beanButtonAction extends SuperAction{

	@Autowired
	private CommonService commonService;

	@RequestMapping(value="/z_db_create_bean")
	public @ResponseBody Result z_db_create_bean(@RequestParam HashMap<String,String> bean) throws Exception {
		Result result = new Result();
		if(SystemUtil.isIDE()) {
			String zid = bean.get("zid");
			if(z.isNotNull(zid)) {
				z_db db = z.dbsMap.get(zid);
				if(z.isNotNull(db)) {
					List<z_db_table> tableList = db.getZ_db_table_list();
					if(tableList.size()>0) {
						try {
							for (z_db_table table : tableList) {
								//生成Bean
								CreateOtherDbBeanFile(db,table);
								//生成SQL文件
								CreateOtherDbSQLFile(db,table);
							}
							result.setCode(Code.SUCCESS);
							result.setMsg("创建成功");
						} catch (Exception e) {
							result.setCode(Code.ERROR);
							result.setMsg("生成文件出错："+StringUtil.ExceptionToString(e));
						}
					}else {
						result.setCode(Code.ERROR);
						result.setMsg("该数据源下未定义表信息");
					}
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("未找到数据源信息");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("zid is null");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("当前非开发环境，无法生成Bean文件");
		}
		return result;
	}

	/**
	 * 创建SQL文件
	 * @param db
	 * @param table
	 * @throws Exception 
	 */
	private void CreateOtherDbSQLFile(z_db db, z_db_table table) throws Exception {
		File f = new File(z.sp.get("project_path")+"\\src\\main\\java\\com\\futvan\\z\\system\\zdb\\"+db.getDbid()+"\\"+StringUtil.firstLetterToUpper(table.getTable_id())+"SQL.xml");
		//如果找到文件删除
		if (f.exists()) {
			f.delete();
		}else{
			if (!f.getParentFile().exists()){
				f.getParentFile().mkdirs();
			}
		}
		//创建文件
		f.createNewFile();

		//创建输入流
		OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
		BufferedWriter writer = new BufferedWriter(write);
		writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		writer.write("<!DOCTYPE mapper PUBLIC \"-//mybatis.org/DTD Mapper 3.0\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
		writer.write("<mapper namespace=\""+db.getDbid()+"_"+table.getTable_id()+"\">\n");
		writer.newLine();

		//JavaBean文件
		String beanName = "com.futvan.z.system.zdb."+db.getDbid()+"."+table.getTable_id();

		//创建查询=======================================================================================================
		writer.write("	<select id=\""+db.getDbid()+"_"+table.getTable_id()+"_select\" parameterType=\""+beanName+"\" resultType=\""+beanName+"\">\n");
		writer.write("		select * from "+table.getTable_id()+" \n");
		writer.write("		<where>\n");
		//添加标准字段条件
		List<z_db_table_column> columnList = table.getZ_db_table_column_list();
		for (z_db_table_column column : columnList) {
			writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
			writer.write("				and "+column.getColumn_id()+" = #{"+column.getColumn_id()+"}\n");
			writer.write("			</if>\n");
		}
		//添加其它条件
		writer.write("			<if test=\"sql_where_other != null\">\n");
		writer.write("				${sql_where_other} \n");
		writer.write("			</if>\n");
		writer.write("		</where>\n");
		//添加排序条件
		writer.write("		<if test=\"sql_order_by != null\">\n");
		writer.write("			order by ${sql_order_by} \n");
		writer.write("		</if>\n");
		writer.write("	</select>\n");
		writer.newLine();
		//创建查询select 自定义SQL=======================================================================================================
		writer.write("	<select id=\""+db.getDbid()+"_"+table.getTable_id()+"_select_sql\" parameterType=\"java.lang.String\" resultType=\""+beanName+"\">\n");
		writer.write("		<![CDATA[ ${_parameter} ]]> \n");
		writer.write("	</select>\n");
		writer.newLine();
		//创建新增=======================================================================================================
		writer.write("	<insert id=\""+db.getDbid()+"_"+table.getTable_id()+"_insert\" parameterType=\""+beanName+"\">\n");
		writer.write("		insert into "+table.getTable_id()+"( \n");
		for (int i = 0; i < columnList.size(); i++) {
			z_db_table_column column = columnList.get(i);
			if(z.isNotNull(table.getTable_pk())) {
				if(!column.getColumn_id().equals(table.getTable_pk())) {
					writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
					writer.write("				"+column.getColumn_id()+",\n");
					writer.write("			</if>\n");
				}
			}else {
				writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
				if(i==columnList.size()-1) {
					writer.write("				"+column.getColumn_id()+"\n");
				}else {
					writer.write("				"+column.getColumn_id()+",\n");
				}
				writer.write("			</if>\n");
			}
		}
		if(z.isNotNull(table.getTable_pk())) {
			writer.write("				"+table.getTable_pk()+"\n");
		}
		writer.write("		)values( \n");
		for (int i = 0; i < columnList.size(); i++) {
			z_db_table_column column = columnList.get(i);
			if(z.isNotNull(table.getTable_pk())) {
				if(!column.getColumn_id().equals(table.getTable_pk())) {
					writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
					writer.write("				#{"+column.getColumn_id()+"},\n");
					writer.write("			</if>\n");
				}
			}else {
				writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
				if(i==columnList.size()-1) {
					writer.write("				#{"+column.getColumn_id()+"}\n");
				}else {
					writer.write("				#{"+column.getColumn_id()+"},\n");
				}
				writer.write("			</if>\n");
			}
		}
		if(z.isNotNull(table.getTable_pk())) {
			writer.write("				#{"+table.getTable_pk()+"}\n");
		}
		writer.write("		) \n");
		writer.write("	</insert>\n");
		writer.newLine();
		//创建删除=======================================================================================================
		writer.write("	<delete id=\""+db.getDbid()+"_"+table.getTable_id()+"_delete\" parameterType=\""+beanName+"\">\n");
		writer.write("		delete from "+table.getTable_id()+" \n");
		writer.write("		<where>\n");
		//添加标准字段条件
		for (z_db_table_column column : columnList) {
			writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
			writer.write("				and "+column.getColumn_id()+" = #{"+column.getColumn_id()+"}\n");
			writer.write("			</if>\n");
		}
		//添加其它条件
		writer.write("			<if test=\"sql_where_other != null\">\n");
		writer.write("				${sql_where_other} \n");
		writer.write("			</if>\n");
		writer.write("		</where>\n");
		writer.write("	</delete>\n");
		writer.newLine();
		writer.write("</mapper>\n");
		writer.close();
		write.close();

	}

	/**
	 * 创建Bean文件
	 * @param db
	 * @param table
	 * @throws Exception 
	 */
	private void CreateOtherDbBeanFile(z_db db, z_db_table table) throws Exception {
		File f = new File(z.sp.get("project_path")+"\\src\\main\\java\\com\\futvan\\z\\system\\zdb\\"+db.getDbid()+"\\"+table.getTable_id()+".java");
		//如果找到文件删除
		if (f.exists()) {
			f.delete();
		}else{
			if (!f.getParentFile().exists()){
				f.getParentFile().mkdirs();
			}
		}
		//创建文件
		f.createNewFile();

		//创建输入流
		OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
		BufferedWriter writer = new BufferedWriter(write);
		writer.write("package com.futvan.z.system.zdb."+db.getDbid()+";\n");
		writer.write("import com.futvan.z.framework.core.SuperBean;\n");
		writer.write("import java.util.List;\n");
		writer.write("public class "+table.getTable_id()+" extends SuperBean{\n");
		//获取字段
		List<z_db_table_column> columnList = table.getZ_db_table_column_list();
		for (z_db_table_column column : columnList) {
			if(!"zid".equals(column.getColumn_id())
					&& !"number".equals(column.getColumn_id())
					&& !"name".equals(column.getColumn_id())
					&& !"seq".equals(column.getColumn_id())
					&& !"pid".equals(column.getColumn_id())
					&& !"create_user".equals(column.getColumn_id())
					&& !"create_time".equals(column.getColumn_id())
					&& !"update_user".equals(column.getColumn_id())
					&& !"update_time".equals(column.getColumn_id())
					&& !"zversion".equals(column.getColumn_id())
					&& !"orgid".equals(column.getColumn_id())
					&& !"remarks".equals(column.getColumn_id())){
				//获取表字段
				if(z.isNotNull(table.getTable_pk()) && table.getTable_pk().equals(column.getColumn_id())) {
					writer.write("	//"+column.getColumn_name()+" 主键字段"+"\n");
				}else {
					writer.write("	//"+column.getColumn_name()+""+"\n");
				}
				if("BIT".equals(column.getColumn_type())) {
					writer.write("	private boolean "+column.getColumn_id()+";\n");
				}else {
					writer.write("	private String "+column.getColumn_id()+";\n");
				}
				writer.newLine();
			}
		}

		//生成get set方法
		for (z_db_table_column column : columnList) {
			if(!"zid".equals(column.getColumn_id())
					&& !"number".equals(column.getColumn_id())
					&& !"name".equals(column.getColumn_id())
					&& !"seq".equals(column.getColumn_id())
					&& !"pid".equals(column.getColumn_id())
					&& !"create_user".equals(column.getColumn_id())
					&& !"create_time".equals(column.getColumn_id())
					&& !"update_user".equals(column.getColumn_id())
					&& !"update_time".equals(column.getColumn_id())
					&& !"zversion".equals(column.getColumn_id())
					&& !"orgid".equals(column.getColumn_id())
					&& !"remarks".equals(column.getColumn_id())){
				//生成get方法
				writer.write("	/**\n");
				writer.write("	* get"+column.getColumn_name()+"\n");
				writer.write("	* @return "+column.getColumn_id()+"\n");
				writer.write("	*/\n");
				if("BIT".equals(column.getColumn_type())) {
					writer.write("	public boolean get"+StringUtil.firstLetterToUpper(column.getColumn_id())+"() {\n");
				}else {
					writer.write("	public String get"+StringUtil.firstLetterToUpper(column.getColumn_id())+"() {\n");
				}
				writer.write("		return "+column.getColumn_id()+";\n");
				writer.write("  	}\n");
				writer.newLine();

				//生成set方法
				writer.write("	/**\n");
				writer.write("	* set"+column.getColumn_name()+"\n");
				writer.write("	* @return "+column.getColumn_id()+"\n");
				writer.write("	*/\n");
				if("BIT".equals(column.getColumn_type())) {
					writer.write("	public void set"+StringUtil.firstLetterToUpper(column.getColumn_id())+"(boolean "+column.getColumn_id()+") {\n");
				}else {
					writer.write("	public void set"+StringUtil.firstLetterToUpper(column.getColumn_id())+"(String "+column.getColumn_id()+") {\n");
				}
				writer.write("		this."+column.getColumn_id()+" = "+column.getColumn_id()+";\n");
				writer.write(" 	}\n");
				writer.newLine();
			}

		}


		writer.write("}\n");
		writer.close();
		write.close();

	}
}
